//
//  BonusGivingViewController.m
//  HQJFacilitator
//
//  Created by mymac on 16/9/22.
//  Copyright © 2016年 Fujian first time iot technology investment co., LTD. All rights reserved.
//

#import "BonusGivingViewController.h"

@interface BonusGivingViewController ()<UITextFieldDelegate>
{
    BOOL isHaveDian;
    BOOL isBonusNil;
    BOOL isUserName;
    CGFloat distance ;
}
@property (nonatomic,strong)UILabel *headerBonusLabel;
@property (nonatomic,strong)UILabel *instructionsLabel;
@property (nonatomic,strong)UIImageView *warningImageView;
@property (nonatomic,strong)UILabel *payerLabel;
@property (nonatomic,strong)UILabel *bonusNumberLabel;
@property (nonatomic,strong)UILabel *ReceivingPartyLabel;
@property (nonatomic,strong)UILabel *TransactionPasswordLabel;
@property (nonatomic,strong)UITextField *bsNumberTextFileld;

@property (nonatomic,strong)UITextField *RPNumerTextFileld;
@property (nonatomic,strong)UITextField *tPswTextFileld;
@property (nonatomic,strong)UIButton *submitButton;
@property (nonatomic,strong)UILabel *canCashLabel;
@property (nonatomic,copy)NSString *bounsStr;
@property (nonatomic,strong)UIImageView *userNamerImageView;
@property (nonatomic,strong)UILabel *userNamerLabel;
@property (nonatomic,copy)NSString *BonusStr;
@end

@implementation BonusGivingViewController

-(UILabel *)headerBonusLabel {
    if (!_headerBonusLabel) {
        _headerBonusLabel = [[UILabel alloc]init];
        _headerBonusLabel.backgroundColor = [ManagerEngine getColor:@"fff2b2"];
        _headerBonusLabel.frame = CGRectMake(0, 64, WIDTH, 44);
        _headerBonusLabel.textAlignment = NSTextAlignmentCenter;
        _headerBonusLabel.font = [UIFont systemFontOfSize:15 weight:.3f];
        [self.view addSubview:_headerBonusLabel];
    }
    
    
    return _headerBonusLabel;
}

-(UIImageView *)warningImageView {
    if (!_warningImageView) {
        _warningImageView = [[UIImageView alloc]init];
        _warningImageView.layer.masksToBounds = YES;
        _warningImageView.layer.cornerRadius = 10;
        _warningImageView.image = [UIImage imageNamed:@"zhuyi"];
        [self.view addSubview: _warningImageView];
    }
    
    
    return _warningImageView;
}

-(UILabel *)instructionsLabel {
    if (!_instructionsLabel) {
        _instructionsLabel = [[UILabel alloc]init];
        _instructionsLabel.font = [UIFont systemFontOfSize:14];
        _instructionsLabel.text = @"积分赠送给名下会员,需扣除10%手续费";
        _instructionsLabel.textColor = [ManagerEngine getColor:@"f54949"];
        [self.view addSubview:_instructionsLabel];
    }
    
    
    
    
    return _instructionsLabel;
}


-(UILabel *)payerLabel {
    
    if (!_payerLabel) {
        _payerLabel = [[UILabel alloc]init];
        _payerLabel.font = [UIFont systemFontOfSize:17];
        [self.view addSubview:_payerLabel];
    }
    
    return _payerLabel;
}
-(UILabel *)bonusNumberLabel {
    if (!_bonusNumberLabel) {
        _bonusNumberLabel = [[UILabel alloc]init];
        _bonusNumberLabel.font = [UIFont systemFontOfSize:17];
        _bonusNumberLabel.text = @"积分数:";
        [self.view addSubview:_bonusNumberLabel];
        
    }
    
    
    return _bonusNumberLabel;
}
-(UITextField *)bsNumberTextFileld {
    if (!_bsNumberTextFileld) {
        _bsNumberTextFileld = [[UITextField alloc]init];
        _bsNumberTextFileld.textColor = [UIColor blackColor];
        _bsNumberTextFileld.backgroundColor = [UIColor whiteColor];
        _bsNumberTextFileld.layer.masksToBounds = YES;
        _bsNumberTextFileld.layer.cornerRadius = 5;
        _bsNumberTextFileld.placeholder = @" 请输入兑现积分数额";
        _bsNumberTextFileld.clearButtonMode = UITextFieldViewModeAlways;
        _bsNumberTextFileld.keyboardType = UIKeyboardTypeDecimalPad;
        _bsNumberTextFileld.delegate = self;
        [self.view addSubview:_bsNumberTextFileld];
    }
    
    return _bsNumberTextFileld;
    
}
-(UILabel *)ReceivingPartyLabel {
    if (!_ReceivingPartyLabel) {
        _ReceivingPartyLabel = [[UILabel alloc]init];
        _ReceivingPartyLabel.font = [UIFont systemFontOfSize:17];
        _ReceivingPartyLabel.text = @"收款方电话:";
        [self.view addSubview:_ReceivingPartyLabel];
    }
    
    
    
    
    return _ReceivingPartyLabel;
}
-(UITextField *)RPNumerTextFileld {
    if (!_RPNumerTextFileld) {
        _RPNumerTextFileld = [[UITextField alloc]init];
        _RPNumerTextFileld.layer.masksToBounds = YES;
        _RPNumerTextFileld.layer.cornerRadius = 5;
        _RPNumerTextFileld.placeholder = @" 请输入收款方电话";
        _RPNumerTextFileld.textColor = [UIColor blackColor];
        _RPNumerTextFileld.backgroundColor = [UIColor whiteColor];
        _RPNumerTextFileld.clearButtonMode = UITextFieldViewModeAlways;
        _RPNumerTextFileld.keyboardType = UIKeyboardTypeNumberPad;
//        _RPNumerTextFileld.secureTextEntry = YES;
        [self.view addSubview:_RPNumerTextFileld];
    }
    
    
    return _RPNumerTextFileld;
}

-(UIImageView *)userNamerImageView {
    if (!_userNamerImageView) {
        _userNamerImageView = [[UIImageView alloc]init];
        _userNamerImageView.image = [UIImage imageNamed:@"man"];
        [self.view addSubview: _userNamerImageView];
    }
    
    
    
    return _userNamerImageView;
}

-(UILabel *)userNamerLabel {
    if (!_userNamerLabel) {
        _userNamerLabel = [[UILabel alloc]init];
        _userNamerLabel.font = [UIFont systemFontOfSize:12];
        _userNamerLabel.textColor = [ManagerEngine getColor:@"f54949"];
        
        [self.view addSubview:_userNamerLabel];
    }
    
    
    return _userNamerLabel;
}

-(UILabel *)TransactionPasswordLabel {
    if (!_TransactionPasswordLabel) {
        _TransactionPasswordLabel = [[UILabel alloc]init];
        _TransactionPasswordLabel.font = [UIFont systemFontOfSize:17];
        _TransactionPasswordLabel.text = @"交易密码:";
        [self.view addSubview:_TransactionPasswordLabel];
    }
    
    
    
    return _TransactionPasswordLabel;
}

-(UITextField *)tPswTextFileld {
    if (!_tPswTextFileld) {
        _tPswTextFileld = [[UITextField alloc]init];
        _tPswTextFileld.layer.masksToBounds = YES;
        _tPswTextFileld.layer.cornerRadius = 5;
        _tPswTextFileld.placeholder = @" 请输入6位交易密码";
        _tPswTextFileld.textColor = [UIColor blackColor];
        _tPswTextFileld.backgroundColor = [UIColor whiteColor];
        _tPswTextFileld.clearButtonMode = UITextFieldViewModeAlways;
        _tPswTextFileld.keyboardType = UIKeyboardTypeNumberPad;
        _tPswTextFileld.secureTextEntry = YES;
        [self.view addSubview:_tPswTextFileld];
    }
    
    
    
    return _tPswTextFileld;
}
-(UILabel *)canCashLabel {
    
    if (!_canCashLabel) {
        _canCashLabel = [[UILabel alloc]init];
        _canCashLabel.font = [UIFont systemFontOfSize:12];
        [self.view addSubview:_canCashLabel];
        
    }
    
    return _canCashLabel;
}


-(UIButton *)submitButton {
    if (!_submitButton) {
        _submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_submitButton setTitle:@"提交" forState:UIControlStateNormal];
        _submitButton.backgroundColor = [ManagerEngine getColor:@"8ae6dc"];
        _submitButton.layer.masksToBounds = YES;
        _submitButton.layer.cornerRadius = 5;
        [self.view addSubview:_submitButton];
    }
    
    
    
    return _submitButton;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [ManagerEngine getColor:@"f5f5f5"];
    _bounsStr = [Manager sharedManager].bonus;
    [self bonusRequst];

    isUserName = NO;
    distance = 30;
    [self content];
    [self signalJudgment];
}

#pragma mark --
#pragma mark --- 积分请求
-(void)bonusRequst {
    
    NSString *urlStr = [NSString stringWithFormat:@"%@bonusTransferToOther/memberid/%@",AppOrg_URL,MmberidStr];
    
    [RequestEngine HQJFacilitatorRequestDetailsUrl:urlStr complete:^(NSDictionary *dic) {
        if ([dic[@"error"]integerValue] == 0) {
            _BonusStr = [NSString stringWithFormat:@"%@",dic[@"result"][@"bonus"]];
            [self bounsNumerLabel];
        }
    } andError:^(NSError *error) {
        
    } ShowHUD:NO];
    
    
}


#pragma mark --
#pragma mark --- 积分数量
-(void)bounsNumerLabel {
    
    
    self.headerBonusLabel.text = [NSString stringWithFormat:@"当前服务商账号有%@个积分",_BonusStr];
    
    [ManagerEngine setTextColor:self.headerBonusLabel FontNumber:[UIFont systemFontOfSize:15 weight:.2f]  AndRange:_BonusStr AndColor:[ManagerEngine getColor:@"f54949"]];
}



#pragma mark --
#pragma mark ---视图内容
-(void)content {
    
    
    /***警示图标****/
    self.warningImageView.sd_layout.
    leftSpaceToView(self.view,20).
    topSpaceToView(self.headerBonusLabel,15).
    heightIs(20).
    widthIs(20);
    
    /****警示文字****/
    CGFloat instructionsRect = [ManagerEngine setTextWidthStr:self.instructionsLabel.text andFont:[UIFont systemFontOfSize:14]];
    self.instructionsLabel.sd_layout.
    leftSpaceToView(self.warningImageView,8).
    topEqualToView(self.warningImageView).heightIs(20).widthIs(instructionsRect);
    
    /******支付方******/
    self.payerLabel.text = [NSString stringWithFormat:@"支付方: %@",Rrealname];
    self.payerLabel.sd_layout.
    leftSpaceToView(self.view,15).
    topSpaceToView(self.instructionsLabel,20).
    heightIs(20).
    widthIs(WIDTH-30);
    
    /******积分数******/
    self.bonusNumberLabel.sd_layout.
    leftEqualToView(self.payerLabel).
    topSpaceToView(self.payerLabel,30).
    heightIs(20).
    widthIs(60);
    
    /******积分数输入框******/
    self.bsNumberTextFileld.sd_layout.
    leftSpaceToView(self.bonusNumberLabel,0).
    topSpaceToView(self.payerLabel,20).
    heightIs(40).
    widthIs(WIDTH-30-60);
    
    
    /****收款方*****/
      CGFloat ReceivingPartyRect = [ManagerEngine setTextWidthStr:self.ReceivingPartyLabel.text andFont:[UIFont systemFontOfSize:17]];
    self.ReceivingPartyLabel.sd_layout.leftEqualToView(self.payerLabel).topSpaceToView(self.bsNumberTextFileld,40).heightIs(20).widthIs(ReceivingPartyRect);
    
    /****手机号码输入框******/
    self.RPNumerTextFileld.sd_layout.leftSpaceToView(self.ReceivingPartyLabel,5).topSpaceToView(self.bsNumberTextFileld,30).heightIs(40).widthIs(WIDTH-30-5-ReceivingPartyRect);
   
    
    
    /****交易密码******/
    self.TransactionPasswordLabel.sd_layout.leftEqualToView (self.payerLabel).topSpaceToView(self.ReceivingPartyLabel,50).heightIs(20).widthIs(80);
    
    /****交易密码输入框*****/
    self.tPswTextFileld.sd_layout.leftSpaceToView(self.TransactionPasswordLabel,0).topSpaceToView(self.ReceivingPartyLabel,40).heightIs(40).widthIs(WIDTH-30-80);
    
    
    /******提交******/
    self.submitButton.sd_layout.leftEqualToView(self.payerLabel).topSpaceToView(self.tPswTextFileld,20).heightIs(40).widthIs(WIDTH-30);
    
}

#pragma mark --
#pragma mark ---信号处理
-(void)signalJudgment {
    
    RACSignal *validPswSignal = [self.tPswTextFileld.rac_textSignal map:^id(id value) {
        return @([self isValidPsw:value]);
    }];
    RACSignal *validBounsSignal = [self.bsNumberTextFileld.rac_textSignal map:^id(NSString *value) {
        
        if ([value isEqualToString:@""]) {
            self.canCashLabel.text = [NSString stringWithFormat:@"对方可得积分:0.00"];
        } else {
            self.canCashLabel.text = [NSString stringWithFormat:@"对方可得积分:%.2f",[value floatValue]*0.9f];
        }
        [self upLayout];
        return @([self textFieldChanged:value]);
    }];
    RACSignal *validNumerSignal = [self.RPNumerTextFileld.rac_textSignal map:^id(NSString * value) {
        if (value.length ==11) {
            if ([value isEqualToString:Mmobile]) {
                [ManagerEngine homeSvpStr:@"自身会员请通过积分转移操作" andcenterView:self.view andStyle:promptViewDefault];
            } else {
                [self numerRequst];

            }

        } else {
            self.userNamerLabel.text = @"";
            [self upLayout];

        }

        
        return @([self numerValid:value]);
    }];
    RAC(self.canCashLabel,textColor) = [validBounsSignal map:^id(NSNumber *values) {
        return [values boolValue]?[ManagerEngine getColor:@"f54949"]:[ManagerEngine getColor:@"999999"];
    }];
    
    RACSignal *signUp = [RACSignal combineLatest:@[validPswSignal,validBounsSignal,validNumerSignal] reduce:^id(NSNumber *pswValid,NSNumber *bounsValid,NSNumber *userValid){
        return @([pswValid boolValue]&&[bounsValid boolValue] &&[userValid boolValue]);
    }];
    [signUp subscribeNext:^(NSNumber * signUpActive) {
        self.submitButton.enabled = [signUpActive boolValue];
        if ([signUpActive boolValue]) {
            self.submitButton.backgroundColor = [ManagerEngine getColor:@"00ccb8"];
            
        } else {
            self.submitButton.backgroundColor = [ManagerEngine getColor:@"8ae6dc"];
            
        }
        
    }];
    [[self.submitButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        if ([_bsNumberTextFileld.text doubleValue]>[_BonusStr doubleValue]) {
            [ManagerEngine homeSvpStr:@"亲，您的积分好像没有那么多哦" andcenterView:self.view andStyle:promptViewDefault];
        } else {
            [self requstGiving];
        }
        HQJLog(@"RACzhong  ");
    }];
    
}

#pragma mark --
#pragma mark ---密码的输入框条件
-(BOOL)isValidPsw:(NSString *)text {
    if (text.length==6) {
        return YES;
    } else if (text.length >6) {
        
        [ManagerEngine homeSvpStr:@"交易密码不能超过6位数" andcenterView:self.view andStyle:promptViewDefault];
        return NO;
    } else {
        return NO;
        
    }
    
    
}

#pragma mark --
#pragma mark ---积分数的输入框条件
-(BOOL)textFieldChanged:(NSString *)text
{
    if ([text floatValue]<=0) {
        return  NO;
    }  else{
        return  YES;
    }
    
}

#pragma mark --
#pragma mark ---手机号的输入框条件
-(BOOL)numerValid:(NSString *)text {
    
    if (text.length==11) {
        return YES;
    }
    return NO;
    
}


#pragma mark --
#pragma mark ---更新布局
-(void)upLayout {
    
    /***可兑换的金额***/
    
    CGFloat cancashRect = [ManagerEngine setTextWidthStr:self.canCashLabel.text andFont:[UIFont systemFontOfSize:12]];
    self.canCashLabel.sd_layout.leftSpaceToView(self.view,WIDTH- cancashRect-15).topSpaceToView(self.bsNumberTextFileld,5).heightIs(20).widthIs(cancashRect);
    
        CGFloat userNamerRect = [ManagerEngine setTextWidthStr:self.userNamerLabel.text andFont:[UIFont systemFontOfSize:12]];
        
        self.userNamerImageView.sd_layout.leftSpaceToView(self.view,WIDTH-20-userNamerRect-15).topSpaceToView(self.RPNumerTextFileld,8).heightIs(12).widthIs(12);
        
        self.userNamerLabel.sd_layout.leftSpaceToView(self.userNamerImageView,5).topEqualToView(self.userNamerImageView).heightIs(12).widthIs(userNamerRect);
    
    
}



#pragma mark --
#pragma mark ---UITextFiled Delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //    NSLog(@"输入的内容为%@",textField.text);
    
    if ([self.bsNumberTextFileld.text rangeOfString:@"."].location==NSNotFound) {
        isHaveDian=NO;
    }
    if ([string length]>0)
        
    {
        if ([self.bsNumberTextFileld.text length]>7)
        {
            [ManagerEngine homeSvpStr:@"亲，输入超出限制了哟" andcenterView:self.view andStyle:promptViewDefault];
            
            return NO;
        }
        
        
        unichar single=[string characterAtIndex:0];//当前输入的字符
        if ((single >='0' && single<='9') || single=='.')//数据格式正确
        {
            
            
            if (single=='.')
            {
                if(!isHaveDian)//text中还没有小数点
                {
                    isHaveDian=YES;
                    return YES;
                }else
                {
                    [ManagerEngine homeSvpStr:@"亲，您已经输入过小数点了" andcenterView:self.view andStyle:promptViewDefault];
                    
                    [self.bsNumberTextFileld.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
                
            }
            else
            {
                if (isHaveDian)//存在小数点
                {
                    //判断小数点的位数
                    NSRange ran=[self.bsNumberTextFileld.text rangeOfString:@"."];
                    
                    NSInteger tt = range.location-ran.location;
                    
                    if (tt <= 2){
                        return YES;
                    }else{
                        [ManagerEngine homeSvpStr:@"亲，您最多输入两位小数" andcenterView:self.view andStyle:promptViewDefault];
                        return NO;
                    }
                }
                else
                {
                    return YES;
                    
                }
                
                
            }
        }else{//输入的数据格式不正确
            [ManagerEngine homeSvpStr:@"亲，您输入的格式不正确" andcenterView:self.view andStyle:promptViewDefault];
            [self.bsNumberTextFileld.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
            
        }
        
    }
    
    else
    {
        return YES;
        
    }
    
}


#pragma mark --
#pragma mark --- 输完手机号请求收款人姓名
-(void)numerRequst {
    NSString *urlStr = [NSString stringWithFormat:@"%@getMemberInfo/memberid/%@/mobile/%@",AppOrg_URL,MmberidStr,_RPNumerTextFileld.text];
    [RequestEngine HQJFacilitatorRequestDetailsUrl:urlStr complete:^(NSDictionary *dic) {
        
        if ([dic[@"error"]integerValue] == 0){
//            [self.userNamerImageView setHidden:NO];
//            [self.userNamerLabel setHidden:NO];
            self.userNamerLabel.text = [NSString stringWithFormat:@"%@",dic[@"result"][@"realname"]];
            [self upLayout];
        }
        if ([dic[@"error"]integerValue] == 48001) {
            [ManagerEngine homeSvpStr:@"无匹配电话号码" andcenterView:self.view andStyle:promptViewDefault];
        }
          } andError:^(NSError *error) {
        
    } ShowHUD:NO];
    
    
}

#pragma mark --
#pragma mark --- 提交请求
-(void)requstGiving {
    if (![self.userNamerLabel.text isEqualToString:@""]) {
        NSString *urlStr = [NSString stringWithFormat:@"%@bonusTransferToOtherAction/amount/%@/tradepwd/%@/memberid/%@/cusMobile/%@",AppOrg_URL,_bsNumberTextFileld.text,_tPswTextFileld.text,MmberidStr,_RPNumerTextFileld.text];
        [RequestEngine HQJFacilitatorRequestDetailsUrl:urlStr complete:^(NSDictionary *dic) {
            NSString *str;
            [str floatValue];
            if ([dic[@"error"]integerValue] == 0) {
                _BonusStr = [NSString stringWithFormat:@"%.2f",[_BonusStr floatValue] - [_bsNumberTextFileld.text floatValue]];
                [self bounsNumerLabel];
                [ManagerEngine customAlert:@"赠送成功" andViewController:self isBack:YES];
            } else{
                [ManagerEngine homeSvpStr:dic[@"result"][@"errmsg"] andcenterView:self.view andStyle:promptViewDefault];
            }
            HQJLog(@"赠送了:%@",dic);

        } andError:^(NSError *error) {
            
        } ShowHUD:YES];

    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
